package com.qc.blogsystemplus.controller;

import com.qc.blogsystemplus.bean.ResponseBean;
import com.qc.blogsystemplus.entity.Article;
import com.qc.blogsystemplus.mapper.ArticleMapper;
import com.qc.blogsystemplus.service.ArticleService;
import com.qc.blogsystemplus.util.JWTUtil;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
public class ArticelController {

    @Autowired
    private ArticleService articleService;

    @GetMapping("/getallarticle")
    public ResponseBean getAllArticle(){
        List<Article> list = articleService.getAllArticle();
        return new ResponseBean(200,"成功",list);
    }

    @RequiresRoles("user")
    @PostMapping("/addarticle")
    public ResponseBean addArticle(@RequestBody Article article) {
        Subject subject = SecurityUtils.getSubject();
        if (subject.isAuthenticated()) {
            String username = JWTUtil.getUsername(subject.getPrincipal().toString());
            int re = articleService.addArticle(article, username);
            return new ResponseBean(200, "更新成功", null);
        } else {
            return new ResponseBean(401, "更新失败", null);
        }
    }

    @RequiresRoles("user")
    @GetMapping("/delarticle")
    public ResponseBean delArticle(@RequestParam("id") int id){
        Subject subject = SecurityUtils.getSubject();
        if (subject.isAuthenticated()) {
            String username = JWTUtil.getUsername(subject.getPrincipal().toString());
            String usernameAr = articleService.getArticle(id).getUsername();

                if (articleService.delArticle(id) != 0 ) {
                    return new ResponseBean(200,"删除成功",null);
                } else {
                    return new ResponseBean(401, "删除失败", null);
                }

        } else {
            return new ResponseBean(401,"未登录",null);
        }
    }

    @RequiresRoles("user")
    @GetMapping("/getmyarticle")
    public ResponseBean getMyarticle() {
        Subject subject = SecurityUtils.getSubject();
        if (subject.isAuthenticated()) {
            String username = JWTUtil.getUsername(subject.getPrincipal().toString());
            List<Article> list = articleService.getArticleByUser(username);
            if (list.isEmpty()) {
                list = null;
            }
            return new ResponseBean(200,"请求成功",list);
        } else {
            return new ResponseBean(401,"未登录",null);
        }
    }

    @GetMapping("/getarticle")
    public ResponseBean getArticleByCate(@RequestParam("category") String category) {
        return new ResponseBean(200,"成功",articleService.getArticleByCate(category));
    }

}
